import { _decorator, Animation, AnimationClip, AnimationState, Component, instantiate, Material, math, MeshRenderer, Node, Prefab, random } from 'cc';
import { gameManger } from './gameManger';
const { ccclass, property } = _decorator;

@ccclass('bulletController')
export class bulletController extends Component {
    @property(Material) red: Material
    @property(Material) blue: Material
    @property(Prefab) bullet: Prefab
    @property(gameManger) gameManger: gameManger
    private animation: Animation = null
    start() {

    }

    update(deltaTime: number) {

    }
    createBullet(number: number) {
        let cube = this.node.children[0]
        this.node.removeAllChildren()
        cube.parent = this.node
        let bulletAry = []
        for (let i = 0; i < number; i++) {
            let random = Math.random()
            let bulletNode = instantiate(this.bullet);
            bulletNode.parent = this.node
            bulletNode.setPosition(0.08125 * i - 0.24375, 0.05, 0)
            if (random > 0.5) {
                bulletAry.push(1)
                let meshrenderer = bulletNode.getComponent(MeshRenderer)
                meshrenderer.setSharedMaterial(this.red, 0)
            } else {
                bulletAry.push(0)
                let meshrenderer = bulletNode.getComponent(MeshRenderer)
                meshrenderer.setSharedMaterial(this.blue, 0)
            }
        }
        return bulletAry
    }
    playAnimation(WrapMode: AnimationClip.WrapMode) {
        if (WrapMode == AnimationClip.WrapMode.Normal) {
            this.node.active = true
        }
        this.animation = this.node.getComponent(Animation)
        this.animation.on(Animation.EventType.FINISHED, this.animationEnd, this)

        let state = this.animation.getState("bullet")
        state.wrapMode = WrapMode
        this.animation.play("bullet")
    }
    animationEnd(type: Animation.EventType, state: AnimationState) {
        if(this.animation.getState("bullet").wrapMode == AnimationClip.WrapMode.Reverse){
            this.animation.off(Animation.EventType.FINISHED, this.animationEnd, this)
            this.node.active = false
            this.gameManger.randomBullet()
        }
    }
}


